<?php

namespace app\model;

use think\Model;

class MerchantBalance extends Model
{
    public function merchant()
    {
        return $this->hasOne(Merchant::class, "id", "mer_id");
    }

    public function lst(): array
    {
        $param = request()->param();
        $data = $this->with("merchant")->when(!empty($param['create_time']), function ($query) use ($param) {
            $query->whereBetween('create_time', [$param['create_time'][0] . " 00:00:00", $param['create_time'][1] . " 23:59:59"]);
        })->when(!empty($param['type']), function ($query) use ($param) {
            $query->where('type', $param['type']);
        })->when(!empty($param['des']), function ($query) use ($param) {
            $query->where('des', $param['des']);
        })->when(!empty($param['searchValue']), function ($query) use ($param) {
            $key = $param['searchKey'];
            $value = $param['searchValue'];
            if ($key == "merchant") {
                $query->whereIn("mer_id", Merchant::whereLike('name', "%$value%")->column("id"));
            }
            if ($key == 'content') $query->where('content', "like", "%$value%");
            if ($key == 'order_sn') $query->where('order_sn', "like", "%$value%");
        })->order(['create_time' => 'desc'])->paginate([
            "list_rows" => $param['size'] ?? 30,
            "page" => $param['page'] ?? 1
        ])->toArray();

        return pageData($data);
    }

    public function download()
    {
        $data = $this->lst();
        $state = [
            1 => "上账",
            2 => "金额调差",
            3 => "退款冲正",
            4 => "充值退款",
            5 => "加油消费"
        ];
        $result = array_map(function ($item) use ($state) {
            return [
                $item['id'],
                $item['merchant']['name'],
                $item['order_sn'],
                $item['content'],
                $item['money'],
                $item['old_money'],
                $item['new_money'],
                $item['type'] == 1 ? "增加" : "减少",
                $state[$item['des']],
                $item['create_time']
            ];
        },$data['list']);
        $header = [
            "ID",
            "商户名称",
            "订单编号",
            "备注",
            "金额",
            "旧金额",
            "新金额",
            "类型",
            "状态",
            "时间"
        ];
        $file = "商户余额记录";
        $last_page = $data['last_page'];
        return excelData(compact("result", "header", "file", "last_page"));
    }
}
